import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Select, Pagination } from 'antd';
import { PlusOutlined, EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';

const { Option } = Select;

const WebApplicationPage = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [editVisible, setEditVisible] = useState(false);
    const [createFormVisible, setCreateFormVisible] = useState(false);
    const [selectedRecord, setSelectedRecord] = useState(null);
    const [searchStatus, setSearchStatus] = useState('');
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [form] = Form.useForm();

    useEffect(() => {
        fetchData();
    }, [searchStatus, currentPage, pageSize]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const response = await fetch('http://127.0.0.1:8080/webApp/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    status: searchStatus,
                    current: currentPage,
                    pageSize: pageSize
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                setData(result.data.content);
                setTotal(result.data.totalElements);
            } else {
                message.error('获取数据失败');
            }
        } catch (error) {
            message.error('请求出错');
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = () => {
        setCreateFormVisible(true);
    };

    const handleEdit = (record) => {
        setSelectedRecord(record);
        setEditVisible(true);
        form.setFieldsValue({
            name: record.name,
            desc: record.descr,
            code: record.code
        });
    };

     const handleCreateSubmit = async (values) => {
        try {
            const response = await fetch('http://127.0.0.1:8080/webApp/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: values.name,
                    desc: values.desc,
                    code: values.code
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('创建成功');
                setCreateFormVisible(false);
                fetchData();
            } else {
                message.error('创建失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };

    const handleUpdateSubmit = async (values) => {
        try {
            const response = await fetch('http://127.0.0.1:8080/webApp/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: selectedRecord.id,
                    name: values.name,
                    desc: values.desc,
                    code: values.code
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('更新成功');
                setEditVisible(false);
                fetchData();
            } else {
                message.error('更新失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };

    const handleEnable = async (record) => {
        try {
            const response = await fetch('http://127.0.0.1:8080/webApp/enable', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: record.id
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('启用成功');
                fetchData();
            } else {
                message.error('启用失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };

    const handleDisable = async (record) => {
        try {
            const response = await fetch('http://127.0.0.1:8080/webApp/disable', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: record.id
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('禁用成功');
                fetchData();
            } else {
                message.error('禁用失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };

    const handleCancel = () => {
        setEditVisible(false);
        setCreateFormVisible(false);
        form.resetFields();
    };

    const handleSearchStatusChange = (value) => {
        setSearchStatus(value); // 设置状态搜索值
    };

    const handleSearch = () => {
        fetchData(); // 执行搜索
    };

    const handlePaginationChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
                    创建
                </Button>
                <Select
                    value={searchStatus}
                    onChange={handleSearchStatusChange}
                    style={{ width: 150 }}
                >
                    <Option value="">全部</Option> {/* 添加“全部”选项 */}
                    <Option value="ENABLED">启用</Option>
                    <Option value="DISABLED">禁用</Option>
                </Select>
                <Button type="primary" onClick={handleSearch}>
                    搜索
                </Button>
            </div>
            <Table
                dataSource={data}
                loading={loading}
                columns={[
                    {
                        title: '名称',
                        dataIndex: 'name',
                        key: 'name',
                    },
                    {
                        title: '编码',
                        dataIndex: 'code',
                        key: 'code',
                    },
                    {
                        title: '描述',
                        dataIndex: 'descr',
                        key: 'descr',
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        key: 'status',
                        render: status => <span>{status.desc}</span>,
                    },
                    {
                        title: '操作',
                        key: 'action',
                        render: (text, record) => (
                            <>
                                <a onClick={() => handleEdit(record)}>编辑</a>

                                <a disabled = {!(record.status.name === 'DISABLED')} onClick={() => handleEnable(record)}>启用</a>
                                |
                                <a disabled = {!(record.status.name === 'ENABLED')} onClick={() => handleDisable(record)}>禁用</a>
                            </>
                        ),
                    },
                ]}
                pagination={false} // 禁用内置分页
            />
            <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                onChange={handlePaginationChange}
                style={{ marginTop: 16 }}
            />
            <Modal
                title="编辑应用"
                visible={editVisible}
                onOk={() => form.submit()}
                onCancel={handleCancel}
                okText="保存"
                cancelText="取消"
            >
                <Form form={form} onFinish={handleUpdateSubmit}>
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input placeholder="请输入名称" />
                    </Form.Item>
                    <Form.Item
                        label="描述"
                        name="desc"
                        rules={[{ required: true, message: '请输入描述' }]}
                    >
                        <Input placeholder="请输入描述" />
                    </Form.Item>
                    {selectedRecord && (
                        <Form.Item
                            label="编码"
                            name="code"
                            rules={[{ required: true, message: '请输入编码' }]}
                        >
                            <Input placeholder="请输入编码" disabled={!!selectedRecord.id} />
                        </Form.Item>
                    )}
                </Form>
            </Modal>
            <Modal
                title="创建应用"
                visible={createFormVisible}
                onOk={() => form.submit()}
                onCancel={handleCancel}
                okText="保存"
                cancelText="取消"
            >
                <Form form={form} onFinish={handleCreateSubmit}>
                    <Form.Item
                        label="名称"
                        name="name"
                        rules={[{ required: true, message: '请输入名称' }]}
                    >
                        <Input placeholder="请输入名称" />
                    </Form.Item>
                    <Form.Item
                        label="编码"
                        name="code"
                        rules={[{ required: true, message: '请输入编码' }]}
                    >
                        <Input placeholder="请输入编码" />
                    </Form.Item>
                    <Form.Item
                        label="描述"
                        name="desc"
                        rules={[{ required: true, message: '请输入描述' }]}
                    >
                        <Input placeholder="请输入描述" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default WebApplicationPage;
